package com.ethink.mdm.facade.impl;

import com.ethink.mdm.api.DictionaryFacade;
import com.ethink.mdm.api.constant.MdmConstant;
import com.ethink.mdm.api.info.CurrencyInfo;
import com.ethink.mdm.api.info.DictionaryInfo;
import com.ethink.mdm.common.mapper.CurrencyQueryMapper;
import com.ethink.mdm.common.mapper.DictionaryMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * mateSku Facade接口实现
 *
 * @author default
 * @date 2022-10-31
 */
@RestController
@Slf4j
@RequestMapping("mdm-service/facade/v1/dictionary")
public class DictionaryFacadeImpl implements DictionaryFacade {

    @Autowired
    private DictionaryMapper dictionaryMapper;

    @Autowired
    private CurrencyQueryMapper currencyQueryMapper;

    @Override
    public List<DictionaryInfo> listDictionaryByGroup(String group) {
        return dictionaryMapper.listDictionaryByGroup(group);
    }

    @Override
    public List<CurrencyInfo> listAllCurrency() {
        List<DictionaryInfo> dictionaryInfoList = dictionaryMapper.listDictionaryByGroup(MdmConstant.DT_CURRENCY_CODE);
        Map<String, String> codeNameMap = dictionaryInfoList.stream().collect(Collectors.toMap(
                DictionaryInfo::getCode, DictionaryInfo::getName
                , (a, b) -> a));
        List<CurrencyInfo> currencyInfoList = currencyQueryMapper.queryAll();
        Map<String, BigDecimal> codeRateMap = currencyInfoList.stream().collect(Collectors.toMap(
                CurrencyInfo::getCode, CurrencyInfo::getCnyRate,
                (a, b) -> a));
        List<CurrencyInfo> list = new ArrayList<>();
        BigDecimal usd2cny = codeRateMap.get("USD");
        BigDecimal cny2usd = new BigDecimal(1).divide(usd2cny, 6, BigDecimal.ROUND_HALF_UP);
        for (DictionaryInfo dictionaryInfo : dictionaryInfoList) {
            CurrencyInfo info = new CurrencyInfo();
            info.setCode(dictionaryInfo.getCode());
            info.setName(dictionaryInfo.getName());
            if ("CNY".equals(dictionaryInfo.getCode())) {
                info.setCnyRate(new BigDecimal(1));
                info.setUsdRate(cny2usd);
            } else if ("USD".equals(dictionaryInfo.getCode())) {
                info.setCnyRate(usd2cny);
                info.setUsdRate(new BigDecimal(1));
            } else {
                BigDecimal cnyRate = codeRateMap.get(dictionaryInfo.getCode());
                info.setCnyRate(cnyRate);
                info.setUsdRate(cnyRate.multiply(cny2usd).setScale(6, BigDecimal.ROUND_HALF_UP));
            }
            list.add(info);
        }
        return list;
    }

}